//
//  STLoginViewController.swift
//  SeaTransportManage
//
//  Created by guopengwen on 2021/11/26.
//

import UIKit
import Foundation
import SnapKit

let PrivacyAgreementConfirm_Key = "STPrivacyAgreementConfirm"
let AppAccountUserPhoneNo_Key = "AppAccountUserPhoneNo"

class STLoginViewController: GPBaseViewController, UITextFieldDelegate {
    
    var phoneNum: String = ""
    var password: String = ""
   
    override func viewDidLoad() {
        super.viewDidLoad()
        let phoneNo = UserDefaults.standard.object(forKey: AppAccountUserPhoneNo_Key)
        addSubviewForPage()
        phoneNum = (phoneNo as? String) ?? ""
        phoneInput.text = phoneNum
        
        let privacy = UserDefaults.standard.object(forKey: PrivacyAgreementConfirm_Key)
        if(privacy == nil) {
            view.addSubview(privacView)
            NotificationCenter.default.addObserver(self, selector: #selector(reloadPrivacView), name: NSNotification.Name("refresh"), object: nil)
        }
    }
    
    @objc func reloadPrivacView() {
        privacView.webView.reload()
    }

    func addSubviewForPage() -> Void {
        
        let bg_Height = relativeHeight(w: 375, h: 288)
        view.addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(bg_Height)
        }
        
        view.addSubview(bottomView)

        let appName: UILabel = UILabel.init()
        appName.text = "欢迎登录海铁货运"
        appName.textColor = UIColor.init(hexString: "#1E1F20", alpha: 1)
        bottomView.addSubview(appName)
        appName.snp.makeConstraints { (make) in
            make.top.equalTo(isShortScreen ? 22 : 42)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(33)
        }
        
        let phoneLabel: UILabel = UILabel.init()
        phoneLabel.text = "手机号"
        phoneLabel.textColor = UIColor.init(hexString: "#1E1F20", alpha: 1)
        bottomView.addSubview(phoneLabel)
        phoneLabel.snp.makeConstraints { (make) in
            make.top.equalTo(appName.snp.bottom).offset(isShortScreen ? 15 : 35 )
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(25)
        }

        bottomView.addSubview(phoneInput)
        phoneInput.snp.makeConstraints { (make) in
            make.top.equalTo(phoneLabel.snp.bottom).offset(11)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(48)
        }

        let psdLabel: UILabel = UILabel.init()
        psdLabel.text = "密码"
        psdLabel.textColor = UIColor.init(hexString: "#1E1F20", alpha: 1)
        bottomView.addSubview(psdLabel)
        psdLabel.snp.makeConstraints { (make) in
            make.top.equalTo(phoneInput.snp.bottom).offset(23)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(25)
        }

        bottomView.addSubview(pswInput)
        pswInput.snp.makeConstraints { (make) in
            make.top.equalTo(psdLabel.snp.bottom).offset(11)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(48)
        }

        bottomView.addSubview(loginBtn)
        loginBtn.snp.makeConstraints { (make) in
            make.top.equalTo(pswInput.snp.bottom).offset(29)
            make.left.equalTo(28)
            make.right.equalTo(-28)
            make.height.equalTo(58)
        }

        loginBtn.addTarget(self, action: #selector(loginAction), for: .touchUpInside)
    }
    
    @objc func loginAction() {
        if ( phoneNum.count == 0 ) {
            self.toastError("请输入手机号")
        }
        // 注释，为了测试账号
        //  else if ( phoneNum.count != 11 ) {
        //    self.toastError("请输入正确的手机号")
        //  }
        else if ( password.count == 0 ) {
            self.toastError("请输入密码")
        } else {
            var param = [String: Any]()
            param["username"] = phoneNum
            param["password"] = NSString.md5EncryptStr(password, bateNum: 32, isLowercaseStr: true)
            
            GPRequestApi.init().login(param) { (isSuccess, response, error)  in
                if(isSuccess) {
                    let responseData = response as! Dictionary<String, Any>
                    let data = responseData["data"] as! Dictionary<String, String>
                    print("token：%@", (data["token"]) ?? "");
                    UserDefaults.standard.set(data["token"], forKey: Authorization_Key)
                    UserDefaults.standard.set(self.phoneNum, forKey: AppAccountUserPhoneNo_Key)
                    let homeVC: STHomeViewController = STHomeViewController.init()
                    let homeNav = UINavigationController.init(rootViewController: homeVC)
                    UIApplication.shared.keyWindow?.rootViewController = homeNav
                } else {
                    self.toastError(error!.msg)
                }
            }
        }
    }
    
    @objc func registerAction() {
        
    }
    
    // MARK: - UITextFieldDelegate
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField.text != nil {
            let str = (textField.text! as NSString).replacingCharacters(in: range, with: string)
            if(textField == phoneInput) {
                phoneNum = str
            } else {
                password = str
            }
        }
        return true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
   
    
    lazy var privacView: STPrivacyAgreementView = {
        let v = STPrivacyAgreementView.init(frame: self.view.bounds)
        return v
    }()
    
    
    lazy var topView: UIImageView = {
        let imgView = UIImageView.init(image: UIImage.init(named: "login-bg"))
        return imgView
    }()
    
    lazy var bottomView: UIView = {
        let top_Height = relativeHeight(w: 375, h: 254)
        let v = UIView.init(frame: CGRect.init(x: 0, y: CGFloat(top_Height), width: kScreenWidth , height: kScreenHeight - CGFloat(top_Height)))
        v.backgroundColor = UIColor.white
        v.setCorndersRaduis(raduis: 32, roundingCorners: [.topLeft, .topRight])
        return v
    }()

    lazy var phoneInput: UITextField = {
        let textField = UITextField.init()
        textField.placeholder = "请输入手机号"
        textField.delegate = self
        textField.borderStyle = .roundedRect
        textField.keyboardType = .numberPad
        textField.layer.borderColor = UIColor.init(hexString: "#8F92A1", alpha: 1).cgColor
        return textField
    }()
    
    lazy var pswInput: UITextField = {
        let textField = UITextField.init()
        textField.placeholder = "请输入至少6位字母数字组合"
        textField.delegate = self
        textField.borderStyle = .roundedRect
        textField.isSecureTextEntry = true
        textField.layer.borderColor = UIColor.init(hexString: "#8F92A1", alpha: 1).cgColor
        return textField
    }()
    
    lazy var loginBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setTitle("登录", for: .normal)
        btn.backgroundColor = UIColor.init(hexString: "#3686FF", alpha: 1)
        btn.layer.cornerRadius = 12
        btn.setTitleColor(UIColor.white, for: UIControl.State.normal)
        return btn
    }()
}
